package com.example.hnvehicle.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.Collection;

/**
 * @Author Shunrai
 * @Date 2023/1/7 22:08
 * @Version 1.0
 * @Description
 */
@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;
    //注入数据源
    @Resource
    private DataSource dataSource;

    @Resource  // 权限不足处理器
    private AccessDeniedHandler accessDeniedHandler;



    @Resource  // 认证成功处理器
    private AuthenticationSuccessHandler authenticationSuccessHandler;

    @Resource  // 认证失败处理器
    private AuthenticationFailureHandler authenticationFailureHandler;



    @Bean
    public PersistentTokenRepository persistentTokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        jdbcTokenRepository.setCreateTableOnStartup(false);
        return jdbcTokenRepository;
    }

        @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService).passwordEncoder(password());
    }

    @Bean
    PasswordEncoder password() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling().accessDeniedHandler(accessDeniedHandler);  // 权限不足处理器
            //退出
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/test/hello").permitAll();
        http.formLogin()   //自定义自己编写的登录页面
                .loginPage("/login.html")  //登录页面设置
                .loginProcessingUrl("/user/login") //登录访问路径
                .successHandler(authenticationSuccessHandler)  // 配置认证成功处理器
                .failureHandler(authenticationFailureHandler) // 配置认证失败处理器
                .defaultSuccessUrl("/index.html",true).permitAll();  //登录成功之后，跳转路径
        http.authorizeRequests()//权限控制
                .antMatchers("/index.html", "/static/**") // 允许访问静态资源和登录页面
                .permitAll()
                .antMatchers( "/test/hello", "/user/login").permitAll()  //设置哪些路径可以直接访问，不需要认证
//                当前登录用户，只有具有admins权限才可以访问这个路径
                //1 hasAuthority方法
                .antMatchers("/addSharedEBike","/addPersonalEBike","addSharedBike",
                "/getAllPersonalEBike","/getAllSharedEBike","/getAllSharedBike",
                        "/deletePersonalEBike","/deleteSharedEBike","/deleteSharedBike",
                        "/getBadSharedBike","/getBadSharedEBike","/updateSharedEBike",
                        "/updateSharedBike","/personalEBike/**","/sharedEBike/**",
                        "/sharedBike/**","/getAllStop","/deleteStop","/addStop",
                        "/addChargingPile","/deleteChargingPile","/getAllChargingPile",
                        "/updateChargingPile","/getPersonalEBikeNum","/getPersonalEBikeNumByCampus",
                        "/getSharedBikeNum","/getRepairSharedBikeNum","/getUseSharedBikeNum",
                        "/getSharedEBikeNum","/getRepairSharedEBikeNum","/getUseSharedEBikeNum",
                        "/getRate","/searchPersonalEBike","/searchSharedBike","/searchSharedEBike",
                        "/getMaxNum").hasAuthority("admin")
                //3 hasRole方法  ROLE_
                .antMatchers("/test/index").hasRole("sale")
                //4 hasAnyRole方法 略
                .anyRequest().authenticated()
                //记住我
//                .and().rememberMe().tokenRepository(persistentTokenRepository())
//                //设置有效时长，单位秒
//                .tokenValiditySeconds(6000)
//                .userDetailsService(userDetailsService)
                .and().cors()  //开启跨域
                .and().csrf().disable(); //关闭csrf防护


    }
}
